#include "Common.h"
#include "Mesh.h"
#include "VertexIndexData.h"
#include "VertexFactory.h"
#include "MeshSerializer.h"

SubMesh::SubMesh(const Mesh* parent)
	: mParent(parent)
	, mShareGeometry(false)
	, mIndexData(NULL)
	, mVertexData(NULL)
	, mVertexFactory(NULL)
{
}

SubMesh::~SubMesh()
{
	SAFE_DELETE(mVertexData);
	SAFE_DELETE(mIndexData);
	SAFE_DELETE(mVertexFactory);
}

VertexFactory* SubMesh::getVertexFactory() const 
{ 
	if (mShareGeometry)
		return mParent->getVertexFactory();

	return mVertexFactory; 
}

Mesh::Mesh(const std::string& name)
	: mVertexData(NULL)
	, mVertexFactory(NULL)
	, mSkeleton(NULL)
{
}

Mesh::~Mesh()
{
	for (SubMeshList::iterator it(mSubMeshes.begin()), end(mSubMeshes.end()); it != end; it++)
		delete *it;
	mSubMeshes.clear();

	SAFE_DELETE(mVertexData);
	SAFE_DELETE(mVertexFactory);
}

void Mesh::Init(bool gpuSkin)
{
	if (mVertexData != NULL)
	{
		if (gpuSkin)
			mVertexFactory = new GPUSkinVertexFactory(mVertexData);
		else
			mVertexFactory = new LocalVertexFactory(mVertexData);
		mVertexFactory->Init();
	}
}

SubMesh* Mesh::CreateSubMesh()
{
	SubMesh* subMesh = new SubMesh(this);
	mSubMeshes.push_back(subMesh);
	return subMesh;
}
